package com.ly.algorithm.leetcode.tree;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @Classname Problem94
 * @Description
 * 给定一个二叉树，返回它的中序 遍历。
 *
 * 示例:
 *
 * 输入: [1.txt,null,2,3]
 *    1.txt
 *     \
 *      2
 *     /
 *    3
 *
 * 输出: [1.txt,3,2]
 * 进阶: 递归算法很简单，你可以通过迭代算法完成吗？
 *
 * @Date 2020/9/14 17:57
 * @Author 冷心影翼
 */



public class Problem94 {
    public static void main(String[] args) {
        TreeNode treeNode = new TreeNode(1);
        treeNode.right = new TreeNode(2);
        treeNode.right.left = new TreeNode(3);
//        treeNode.right.right = new TreeNode(4);
//        treeNode.right.left.right = new TreeNode(7);
        Solution94 solution94 = new Solution94();
        List<Integer> list = solution94.inorderTraversal(treeNode);
        List<Integer> list2 = solution94.inorderTraversal2(treeNode);
        System.out.println(list);
        System.out.println(list2);

    }
}

class Solution94 {

    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        inorder(res,root);
        return res;
    }
    public List<Integer> inorderTraversal2(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        inorderUseStack(res,root);
        return res;
    }

    public void inorder(List<Integer> res,TreeNode root) {
        if(root == null) {
            return;
        }
        inorder(res,root.left);
        res.add(root.val);
        inorder(res,root.right);
    }

    public void inorderUseStack(List<Integer> res,TreeNode root) {
        if(root == null) {
            return;
        }
        Stack<TreeNode> stack = new Stack<>();
        while (root!=null || stack.size()>0) {
           while (root!=null) {
               stack.push(root);
               root = root.left;
           }
           TreeNode pop = stack.pop();
           res.add(pop.val);
           root = pop.right;
        }
    }
}